package ahblue.cn.tanzi.ui.circle;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.Result;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.jmessage.im.pickerimage.utils.ScreenUtil;
import ahblue.cn.tanzi.model.circle.CircleDetailCenter;
import ahblue.cn.tanzi.model.circle.CircleDetailTop;
import ahblue.cn.tanzi.model.home.ArticleCategory;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.model.user.UserModel;
import ahblue.cn.tanzi.ui.base.BaseActivity;
import ahblue.cn.tanzi.ui.home.article.ArticleListFragment;
import ahblue.cn.tanzi.util.DensityUtils;
import ahblue.cn.tanzi.util.GlideApp;
import ahblue.cn.tanzi.util.PinkJSON;
import ahblue.cn.tanzi.util.ScreenUtils;
import ahblue.cn.tanzi.util.VipUtils;
import ahblue.cn.tanzi.view.ScaleTransitionPagerTitleView;
import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CircleDetailActivity extends BaseActivity {

    // 顶部
    @BindView(R.id.textViewTitle)
    TextView mTextViewTitle;
    @BindView(R.id.imageButtonRight)
    ImageButton mImageButtonRight;

    @BindView(R.id.iv_circle_main_v2_headpic)
    ImageView mImageViewCircleHead;
    @BindView(R.id.tv_circle_main_v2_title)
    TextView mTextViewCircleTitle;
    @BindView(R.id.tv_circle_main_v2_hot)
    TextView mCircleMainHot;
    @BindView(R.id.tv_circle_main_v2_name)
    TextView mCircleMainName;
    @BindView(R.id.tv_circle_main_v2_person)
    TextView mCircleMainPerson;
    @BindView(R.id.tv_circle_main_v2_topic)
    TextView mCircleMainTopic;

    @BindView(R.id.tv_intro)
    TextView mTextViewIntro;
    @BindView(R.id.tv_circle_main_v2_value)
    TextView mTextViewCircleValue;
    @BindView(R.id.vp_circle_main_v2_user_start)
    RecyclerView mRecyclerViewUserStart;
    @BindView(R.id.tv_circle_main_v2_join)
    TextView mTextViewJoin;

    @BindView(R.id.tl_article_page_indicator)
    MagicIndicator mTabLayoutPage;
    @BindView(R.id.vp_article_viewpager)
    ViewPager mViewPagerArticle;

    @BindDrawable(R.drawable.shape_0077ff_2dp)
    Drawable mDrawableInCircle;

    @BindView(R.id.rl_circle_main_v2_join)
    RelativeLayout mRelativeLayoutAddCircle;

    @BindView(R.id.sv_circle_shot_detail_content)
    ScrollView svCircleShotDetailContent;

    //标识是否滑动到顶部
    private boolean isScrollToStart = false;
    //标识是否滑动到底部
    private boolean isScrollToEnd = false;

    private ArticleListFragment articleListFragment;
    private CircleListFragment circleListFragment;
    private CircleArticleListFragment circleArticleListFragment;

    private static final int CODE_TO_START = 0x001;
    private static final int CODE_TO_END = 0x002;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_TO_START:
                    //重置标志“滑动到顶部”时的标志位
                    isScrollToStart = false;
                    break;
                case CODE_TO_END:
                    //重置标志“滑动到底部”时的标志位
                    isScrollToEnd = false;
                    break;
                default:
                    break;
            }
        }
    };

    public final static String ARG_CIRCLE_ID = "ARG_CIRCLE_ID";

    private LoginResultModel mLoginResultModel;
    private int mCircleId;

    // 此圈子是否在已经加入的圈子列表中
    private boolean mIsInMyCircles;
    public CircleDetailTop mModel = new CircleDetailTop();
    private List<ArticleCategory> mArticleCategoryList = new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_detail);
        ButterKnife.bind(this);
        //判断是不是充值会员
        if (!VipUtils.checkVip(this)) {
            finish();
            return;
        }

        // 获取登陆信息
        mLoginResultModel = LoginResultModel.getUserModel(this, LoginResultModel.class);
        if (mLoginResultModel == null) {
            finish();
            return;
        }

        // 取得圈子id
        final Intent intent = getIntent();
        mCircleId = intent.getIntExtra(ARG_CIRCLE_ID, 0);

        if (mCircleId == 0) {
            finish();
            return;
        }

        // 判断此圈子用户有没有加入
        String strCircleId = Integer.toString(mCircleId);
        for (String s : mLoginResultModel.circle_id) {
            if (s.equals(strCircleId)) {
                mIsInMyCircles = true;
                break;
            }
        }

        initData();
        initView();
    }

    private void initData() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotCircleDetailsTop(mCircleId, mCircleDetailTopCallback);
        repo.getBigShotCircleDetailsCenter(mCircleId, mCircleDetailCenterCallback);

        ArticleCategory ac = new ArticleCategory();
        ac.setId(1);
        ac.setCategoryTitle("介绍");
        mArticleCategoryList.add(ac);

        ac = new ArticleCategory();
        ac.setId(2);
        ac.setCategoryTitle("动态");
        mArticleCategoryList.add(ac);

        ac = new ArticleCategory();
        ac.setId(3);
        ac.setCategoryTitle("文章");
        mArticleCategoryList.add(ac);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        mViewPagerArticle.getLayoutParams().height = ScreenUtils.getScreenHeight(getApplicationContext())
                - ScreenUtils.getStatusHeight(getApplicationContext()) - (int)getResources().getDimension(R.dimen.actionBar_height);
        svCircleShotDetailContent.scrollTo(0,0);
        mViewPagerArticle.requestDisallowInterceptTouchEvent(false);
        svCircleShotDetailContent.requestDisallowInterceptTouchEvent(false);
        svCircleShotDetailContent.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                //滚动到顶部，ScrollView存在回弹效果效应（这里只会调用两次，如果用<=0,会多次触发）
                if (svCircleShotDetailContent.getScrollY() == 0) {
                    setFragmentCanScroll(false);
                    //过滤操作，优化为一次调用
                    if (!isScrollToStart) {
                        isScrollToStart = true;
                        mHandler.sendEmptyMessageDelayed(CODE_TO_START, 200);
                        Log.e("CustomScrollView", "toStart");
                    }
                } else {
                    View contentView = svCircleShotDetailContent.getChildAt(0);
                    if (contentView != null && contentView.getMeasuredHeight() == (svCircleShotDetailContent.getScrollY() + svCircleShotDetailContent.getHeight())) {
                        //滚动到底部，ScrollView存在回弹效果效应
                        setFragmentCanScroll(true);
                        //优化，只过滤第一次
                        if (!isScrollToEnd) {
                            isScrollToEnd = true;
                            mHandler.sendEmptyMessageDelayed(CODE_TO_END, 200);
                            Log.e("CustomScrollView", "toEnd");
                        }
                    }else {
                        setFragmentCanScroll(false);
                    }
                }
            }
        });
        mTextViewTitle.setText(R.string.circle_detail_title);
        mImageButtonRight.setImageResource(R.drawable.navigation_icon_share);

        if (mIsInMyCircles) {
            mTextViewJoin.setText("进入圈子");
            mRelativeLayoutAddCircle.setBackground(mDrawableInCircle);
        }

        CommonNavigator cn = new CommonNavigator(this);
        cn.setAdapter(mNavigatorAdapter);
        mTabLayoutPage.setNavigator(cn);

        ArticleCategoryAdapter adapter = new ArticleCategoryAdapter(getSupportFragmentManager(), mArticleCategoryList);
        mViewPagerArticle.setAdapter(adapter);
        ViewPagerHelper.bind(mTabLayoutPage, mViewPagerArticle);
    }

    private void setFragmentCanScroll(boolean canScroll){
        if (articleListFragment != null){
            articleListFragment.setCanScrollable(canScroll);
        }
        if (circleListFragment != null){
            circleListFragment.setCanScrollable(canScroll);
        }
        if (circleArticleListFragment != null){
            circleArticleListFragment.setCanScrollable(canScroll);
        }
    }

    // 更新圈子顶部信息
    private void updateTop(CircleDetailTop data) {
        GlideApp.with(this).load(data.head_portrait)
                .placeholder(R.drawable.user_default_avatar)
                .error(R.drawable.user_default_avatar)
                .into(mImageViewCircleHead);

        mTextViewCircleTitle.setText(data.circle_name);
        mCircleMainHot.setText(data.circle_sign);
        mCircleMainName.setText("圈主 " + data.leader);
        mCircleMainPerson.setText(Integer.toString(data.user_count));
        mCircleMainTopic.setText(Integer.toString(data.dynamic_count));
    }

    // 更新圈子中间信息
    private void updateCenter(CircleDetailCenter data) {
        mTextViewIntro.setText(data.simple_introduce);
        mTextViewCircleValue.setText(data.circle_value);

        UserStartAdapter adapter = new UserStartAdapter(Arrays.asList(data.user_list));
        mRecyclerViewUserStart.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mRecyclerViewUserStart.setAdapter(adapter);
    }

    // 单击返回按钮
    @OnClick(R.id.imageButtonLeft)
    void onClickLeftButton() {
        finish();
    }

    // 分享
    @OnClick(R.id.imageButtonRight)
    void onClickRightButton() {

    }

    // 用户单击"加入圈子"按钮
    @OnClick(R.id.rl_circle_main_v2_join)
    void onClickCircleJoin() {
        if (mIsInMyCircles) {
            final Intent intent = new Intent(this, CircleDynamicListActivity.class);
            intent.putExtra("CircleId", mCircleId);
            startActivity(intent);
        } else {
            RemoteRepository repo = RemoteRepository.getsInstance();
            repo.getBigShotCommentInfoCircle(mLoginResultModel.token, mCircleId, mCallbackAddCircle);
        }
    }

    private ApiCallback<CircleDetailTop> mCircleDetailTopCallback = new ApiCallback<CircleDetailTop>() {


        @Override
        public void onSuccess(CircleDetailTop data) {
            mModel = data;
            updateTop(data);
        }

        @Override
        public void onFailed(String errorMsg) {

        }
    };


    private ApiCallback<CircleDetailCenter> mCircleDetailCenterCallback = new ApiCallback<CircleDetailCenter>() {
        @Override
        public void onSuccess(CircleDetailCenter data) {
            updateCenter(data);
        }

        @Override
        public void onFailed(String errorMsg) {

        }
    };

    /**
     * 加入圈子接口的回调接口
     */
    private ApiCallback<Result> mCallbackAddCircle = new ApiCallback<Result>() {
        @Override
        public void onSuccess(Result data) {
            mTextViewJoin.setText("进入圈子");
            mIsInMyCircles = true;
            mLoginResultModel.circle_id.add(Integer.toString(mCircleId));

            LoginResultModel.putUserModel(CircleDetailActivity.this, PinkJSON.toJSON(mLoginResultModel).toString());
        }

        @Override
        public void onFailed(String errorMsg) {

        }
    };

    class UserStartAdapter extends BaseQuickAdapter<CircleDetailCenter.UserStart, BaseViewHolder> {

        UserStartAdapter(@Nullable List<CircleDetailCenter.UserStart> data) {
            super(R.layout.item_circle_main_v2, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, CircleDetailCenter.UserStart item) {
            final ImageView iv = helper.getView(R.id.iv_item_circle_main_v2);
            GlideApp.with(iv).load(item.member_avatar)
                    .placeholder(R.drawable.user_default_avatar)
                    .error(R.drawable.user_default_avatar)
                    .into(iv);

            helper.setText(R.id.tv_item_circle_main_v2_type, item.circle_position);
            helper.setText(R.id.tv_item_circle_main_v2_name, item.member_name);
        }
    }

    CommonNavigatorAdapter mNavigatorAdapter = new CommonNavigatorAdapter() {

        @Override
        public int getCount() {
            return mArticleCategoryList.size();
        }

        @Override
        public IPagerTitleView getTitleView(Context context, int index) {
            ScaleTransitionPagerTitleView colorTransitionPagerTitleView = new ScaleTransitionPagerTitleView(context);
            colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.grey));
            colorTransitionPagerTitleView.setSelectedColor(getResources().getColor(R.color.blue_press));
            colorTransitionPagerTitleView.setTextSize(15);
            colorTransitionPagerTitleView.setText(mArticleCategoryList.get(index).getCategoryTitle());
            colorTransitionPagerTitleView.setOnClickListener(view -> mViewPagerArticle.setCurrentItem(index));

            return colorTransitionPagerTitleView;
        }

        @Override
        public IPagerIndicator getIndicator(Context context) {
            LinePagerIndicator indicator = new LinePagerIndicator(context);
            indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
            indicator.setLineHeight(DensityUtils.dp2px(context, 1.5f));
            indicator.setLineWidth(UIUtil.dip2px(context, 16));
            indicator.setYOffset(DensityUtils.dp2px(context, 3));
            indicator.setColors(getResources().getColor(R.color.blue_press));
            return indicator;
        }
    };


    /**
     * 文章分类ViewPager的adapter。
     */
    class ArticleCategoryAdapter extends FragmentPagerAdapter {

        private List<ArticleCategory> mCategoryList;

        ArticleCategoryAdapter(FragmentManager fm, List<ArticleCategory> data) {
            super(fm);

            mCategoryList = data;
        }

        @Override
        public Fragment getItem(int i) {
            ArticleCategory category = mCategoryList.get(i);
            if (category.getId() == 1) {
                articleListFragment = ArticleListFragment.newInstance(category.getId(), "circle", "",mCircleId);
                return articleListFragment;
            } else if (category.getId() == 2){
                circleListFragment = CircleListFragment.newInstance(mCircleId);
                return circleListFragment;
            } else if (category.getId() == 3){
                circleArticleListFragment = CircleArticleListFragment.newInstance(mCircleId);
                return circleArticleListFragment;
            }
            return ArticleListFragment.newInstance(category.getId(), "circle", "",mCircleId);
        }

        @Override
        public int getCount() {
            return mCategoryList.size();
        }
    }


    private void getData() {
        UserModel.getUserInfo(this, LoginResultModel.getToken(this), new UserModel.UserInfoLoginStatus() {
            @Override
            public void conver(UserModel m) {
                boolean isVip = false;
                //获取过期时间
                String expiredTime  = m.expired_time;
                //判断用户是否是充值会员，过期的充值会员也不算充值会员
                if (expiredTime == null || "".equals(expiredTime.trim())){
                    isVip = false;
                }
            }
        });
    }
}
